from google.appengine.api import users

from src.model import Message, UserPrefs
from src.moderation.moderate import Commands
from base import BaseHandler
from src.utilities.cache import memoize
import urllib
import urlparse

class MainHandler(BaseHandler):

    def head(self):
        self.get()
    
    @staticmethod
    def userprefs_for_user(user):
        return UserPrefs.gql("WHERE user = :1", user).get()

    def current_user(self):
        user = users.get_current_user()
        if user:
            return MainHandler.userprefs_for_user(user)
        else:
            return None
        
    def get(self):
        if self.current_user() is None:
            if users.get_current_user() is None:
                self.render_template('main.html', {'parent': self.request.get('parent')})
            else:
                self.render_template('nickname.html', {})
        else:
            self.render_template('main.html', {'user': self.current_user(),})        

    def post(self):
        person = self.current_user()
        if not person.muter.mute:
            message = Message()
            message.person = self.current_user()
            text = self.request.get('text').strip()
            if text:
                if not(users.is_current_user_admin() and self.moderator_instruction(text)):
                    message.set_formatted_text(text)
                    message.put()
        self.response.out.write('')
            
    def moderator_instruction(self, text):
        return Commands().process(text)